package org.example.server;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket/{userId}")
public class MyWebSocket {
 private Session session;
 private String userId;
 private static CopyOnWriteArraySet<MyWebSocket> webSockets =new
CopyOnWriteArraySet<>();
 // 用来存在线连接用户信息
 private static ConcurrentHashMap<String,Session> sessionPool = new ConcurrentHashMap<String,Session>();
 @OnOpen
 public void onOpen(Session session, @PathParam("userId") String userId) {
 System.out.println("---------------------> on open");
 this.session = session;
 this.userId = userId;
 webSockets.add(this);
 sessionPool.put(userId, session);
 }
 @OnClose
 public void onClose() {
 webSockets.remove(this);
 sessionPool.remove(this.userId);
 }
 @OnMessage
 public void onMessage(String message) {
 System.out.println("[websocket] 收到客户端消息: " + message);
 }
 @OnError
 public void onError(Session session, Throwable error) {
 error.printStackTrace();
 }
 public void sendMoreMessage(String[] userIds, String message) {
 for(String userId : userIds) {
 Session session = sessionPool.get(userId);
 if(session != null && session.isOpen()) {
 session.getAsyncRemote().sendText(message);
 }
 }
 }
}
